import api from '@/network/api'

import { useEffect,useReducer,useState } from 'react'
import bannerState from '@/reducer/banner/state'
import getBannerListAction, { deleteBannerAction } from '@/reducer/banner/action'
import bannerReducer from '@/reducer/banner'

import { Table,Image,Button } from 'antd'
import { Link } from 'umi'


const BannerList = () => {
    const columns = [
        {title: '活动名称',key: 'title',dataIndex: 'title'},
        {title: '活动链接',key: 'link',dataIndex: 'link',
            render: (link) => {
                return <a href={link}>点击预览活动页</a>
            }
        },
        {title: '活动封面',key: 'imgurl',dataIndex: 'imgurl',width: 240,
            render: (imgurl,recode) => {
                return <Image style={{objectFit: 'cover'}} src={imgurl} alt={recode.title} height={250} width={240}/>
            }
        },
        {
            title: '操作',
            render: (_,recode) => {
                return (
                    <>
                        <Button style={{marginRight: '12px'}} type='primary'>
                            <Link to={`/banner/edit/${recode.objectId}`}  type="primary">编辑</Link>
                        </Button>
                        <Button onClick={() =>handleDeleteBanner(recode)} type="danger">删除</Button>
                    </>
                )
            }
        }
    ]
    const [loading,setLoading] = useState(true)
    const [{ bannerList },dispatch] = useReducer(bannerReducer,bannerState)
    
    const initBannerList = async () => {
        let bannerRes = await api.getBanner()
        if (bannerRes.code === 200) {
            setLoading(false)
            dispatch(getBannerListAction(bannerRes.data))
        }
    }
    const handleDeleteBanner = async(recode) => {
        const res = await api.deleteBanner(recode)
        if (res.code === 200) {
            dispatch(deleteBannerAction(recode))
        }
    }
    useEffect(() => {
        initBannerList()
    },[])
    return (
        <Table 
        columns={columns}
        dataSource={bannerList}
        loading={loading}
        bordered={true}
        rowKey={recode => recode.objectId}
        />
    )
}
export default BannerList